package com.ibbi.admin.client.session;

import com.allen_sauer.gwt.log.client.Log;

import corelib.client.jsonrpc.exception.IncompatibleJSONRemoteServiceException;
import corelib.client.jsonrpc.exception.UnexpectedJSONMessageException;
import corelib.client.jsonrpc.impl.platform.ErrorCode;
import corelib.client.jsonrpc.impl.platform.ServiceError;
import corelib.client.jsonrpc.impl.platform.ServiceErrorParser;
import corelib.client.ui.widget.messagebox.SimpleMessageBox;

public class ErrorHandler {
	
	public static void handleServiceError(Throwable caught) {
		ServiceError serviceError = convertToServiceError(caught);
		SimpleMessageBox.error("Error", caught.getMessage(), null);
		Log.error("Unexpected Error: " + serviceError, caught);
	}
	
	public static ServiceError convertToServiceError(Throwable error) {
		Log.debug("error : " + error.getMessage());
		if (error instanceof IncompatibleJSONRemoteServiceException) {
			IncompatibleJSONRemoteServiceException incompatible = (IncompatibleJSONRemoteServiceException) error;
			return new ServiceError(ErrorCode.ServerInternal, incompatible.getMessage(), incompatible.getText());
		}
		if (error instanceof UnexpectedJSONMessageException) {
			UnexpectedJSONMessageException invalid = (UnexpectedJSONMessageException) error;
			ServiceError serviceError = ServiceErrorParser.parseJsonException(invalid.getText());
			if (serviceError != null) {
				return serviceError;
			}
			return new ServiceError(ErrorCode.InvalidRequest, invalid.getMessage(), invalid.getText());
		}
		return new ServiceError(ErrorCode.Unexpected, error.getMessage());
	}

}
